import React, { useMemo } from 'react';
import { pick, isEmpty, isNil } from 'lodash-es';

import { useLatest } from '@/hooks';

import { Widget } from '../widget';
import { type TWidget } from '../../register';

type TProps = {
    getWidgets?: () => TWidget[];
};

const WidgetRender = (props: React.PropsWithChildren<TProps>) => {
    const latestProps = useLatest({ getWidgets: props.getWidgets });

    const widgets = useMemo<TWidget[] | null>(() => {
        if (isNil(latestProps.current.getWidgets)) return null;
        return latestProps.current.getWidgets();
    }, [latestProps]);

    if (isEmpty(widgets)) return null;

    return (
        <>
            {(widgets ?? []).map((item) => {
                const { layout, style } = item;
                return (
                    <Widget
                        {...pick(layout, ['width', 'height', 'left', 'top', 'zIndex'])}
                        style={style}
                        element={item.element}
                        animateCss={item.animateCss}
                        key={item.id}
                        control={item.control}
                        name={item.widgetName}
                        id={item.id}
                        groupFilterId={item.groupFilterId}
                    />
                );
            })}
        </>
    );
};

export {
    //
    WidgetRender,
};

export type {
    //
    TProps as TWidgetRenderProps,
};
